package com.yksj.healthtalk.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.yksj.healthtalk.comm.imageload.ImageLoader;
import com.yksj.healthtalk.entity.AccountEntity;
import com.yksj.healthtalk.entity.BaseInfoEntity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.friend.FriendInformUI;
import com.yksj.healthtalk.ui.salon.SalonInformationActivity;
import com.yksj.healthtalk.ui.salon.SalonNewActivity;
import com.yksj.healthtalk.utils.FileUtils;

public class GroupListAdapter extends BaseAdapter implements ListAdapter {
	ArrayList<Object> data;
	Context context;
	LayoutInflater inflater;
	private boolean isPersonNumber = false; // 是否需要更多 选项
	private boolean isInvite = false;
	private ArrayList<Integer> selects = new ArrayList<Integer>();
	public static final int NUMBER = 30;
	private ImageLoader imageLoader;
	boolean isRefresh = true;
	private int indexStart;
	private int indexEnd;
	private AppData mAppData;
	private SearchIntoInfoListener searchIntoInfoListener;

	public GroupListAdapter(Context applicationContext, ArrayList<Object> data) {
		this.data = data;
		this.context = applicationContext;
		inflater = LayoutInflater.from(context);
		imageLoader = new ImageLoader(applicationContext);
		mAppData = HTalkApplication.getAppData();
	}

	@Override
	public int getCount() {
		int size = data.size();
		return size;
	}

	@Override
	public Object getItem(int position) {
		// return map.get(position);
		Object obj = data.get(position);
		if (obj instanceof AccountEntity)
			return (AccountEntity) obj;
		else if (obj instanceof String)
			return obj;
		else
			return ((BaseInfoEntity) data.get(position)).getId();
	}

	@Override
	public long getItemId(int arg0) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		viewHolder holder = null;
//		Log.i("test", "getView -----------------------");
		if (convertView == null || convertView.getTag() == null) {
			holder = new viewHolder();
			convertView = inflater.inflate(R.layout.group_item, null);
			holder.image = (ImageView) convertView.findViewById(R.id.head_image);
			holder.sex = (ImageView) convertView.findViewById(R.id.head_sex);
			holder.name_tv = (TextView) convertView.findViewById(R.id.name);
			holder.note_tv = (TextView) convertView.findViewById(R.id.note);
			holder.select = (ImageView) convertView.findViewById(R.id.icon);
			holder.dele = (TextView) convertView.findViewById(R.id.item_dele);
			holder.number = (TextView) convertView.findViewById(R.id.number);
			holder.line = (LinearLayout) convertView
					.findViewById(R.id.item_line);
			holder.v = (ImageView) convertView.findViewById(R.id.v);
			holder.lay = (LinearLayout) convertView.findViewById(R.id.note_lay);
			convertView.setTag(holder);
		} else {
			holder = (viewHolder) convertView.getTag();
		}
        
		holder.image.setTag(position);
		
		Object obj = data.get(position);
		if (obj instanceof String)
			obj = mAppData.cacheInformation.get((String) obj);

		// 适配群
		if (obj instanceof GroupInfoEntity) {
			// holder.lay.setVisibility(View.GONE);
			GroupInfoEntity group = (GroupInfoEntity) obj;
			holder.v.setImageResource(R.drawable.ic_cross);

			if (isPersonNumber)
				holder.number.setText(group.getPersonNumber());

			if (group.isSalon())
				holder.v.setVisibility(View.VISIBLE);
			else
				holder.v.setVisibility(View.INVISIBLE);

			String savepath = group.getNormalHeadIcon();
			if (group.getId().equals("-102")) {
				holder.image.setBackgroundResource(0);
			}
			holder.image.setOnClickListener(new onClick(position, true, group
					.getCreateCustomerID().equals(SmartFoxClient.getSmartFoxClient().getUserId())));
			if(isRefresh && !savepath.contains("assets")){
				imageLoader.displayImage(savepath, holder.image, "", true);
//				group.setNormalHeadIcon(FileUtils.getHeaderRootPath()+savepath.substring(savepath.lastIndexOf("/")+1));
			}else{
				FileUtils.setImage(context, holder.image, savepath, true, "");
			}
			holder.name_tv.setText(group.getName());
			holder.note_tv.setText(group.getDescription());
		}

		// 适配好友
		if (obj instanceof CustomerInfoEntity) {
			CustomerInfoEntity cus = (CustomerInfoEntity) obj;
			String savepath = cus.getNormalHeadIcon();

			if (cus.isShow() || cus.isAudit())
				holder.v.setVisibility(View.VISIBLE);
			else
				holder.v.setVisibility(View.INVISIBLE);

			if (selects.contains(position))
				holder.select.setVisibility(View.VISIBLE);
			else
				holder.select.setVisibility(View.GONE);

			if (!isInvite)
				holder.image.setOnClickListener(new onClick(position, false,
						false));
			if (isRefresh && !savepath.contains("assets")) {
				imageLoader.displayImage(savepath, holder.image, cus.getSex(), false);
//				if(!"".equals(savepath))cus.setNormalHeadIcon(FileUtils.getHeaderRootPath()+savepath.substring(savepath.lastIndexOf("/")+1));
			}else{
				FileUtils.setImage(context, holder.image, savepath, false,cus.getSex());
			}
			
			if (!cus.getPhoneName().equals(""))
				holder.name_tv.setText(cus.getPhoneName());
			else
				holder.name_tv.setText(cus.getName() + "(" + cus.getUsername()
						+ ")");
			holder.note_tv.setText(cus.getCusMessag());
			holder.sex
					.setImageResource(cus.getSex().equals("W") ? R.drawable.women
							: R.drawable.man);
			holder.sex.setVisibility(View.VISIBLE);
		}

		// 适配多账号
		if (obj instanceof AccountEntity) {
			holder.v.setVisibility(View.GONE);
			holder.line.setVisibility(View.GONE);
			holder.dele.setBackgroundResource(R.drawable.login_dele);
			if(selects.contains(position))
				holder.dele.setVisibility(View.VISIBLE);
			else
				holder.dele.setVisibility(View.GONE);
			AccountEntity entity = (AccountEntity) obj;
			String savepath = entity.getFace();
			
			imageLoader.displayImage(savepath, holder.image, entity.getSex(), false);
			holder.name_tv.setText(entity.getName());
			holder.name_tv.setTextColor(Color.BLACK);
			holder.note_tv.setText(entity.getAccount());
			holder.note_tv.setTextColor(Color.BLACK);

			holder.sex.setVisibility(View.GONE);
			convertView.setBackgroundResource(0);
		}
		return convertView;
	}

	public class viewHolder {
		LinearLayout line;
		LinearLayout lay;
		ImageView v;
		ImageView image; // 头像
		ImageView sex; // 性别
		TextView name_tv; // 名称
		TextView note_tv; // 简介
		ImageView select;
		TextView dele;
		TextView number;
		boolean isRefresh = true;
	}

	private class onClick implements OnClickListener {
		boolean isGroup;
		int position;
		boolean isEditor;

		public onClick(int position, boolean isGroup, boolean isEditor) {
			this.isGroup = isGroup;
			this.position = position;
			this.isEditor = isEditor;
		}

		@Override
		public void onClick(View v) {
			String id = (String) GroupListAdapter.this.getItem(position);
			String groupName = "";
			Class clazz;
			String key = "id";
			if (!isGroup) {
				clazz = FriendInformUI.class;
			} else if (isEditor) {
				clazz = SalonNewActivity.class;
				key = "groupId";
			} else
				clazz = SalonInformationActivity.class;
//			Intent i = new Intent(context, clazz);
//			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			i.putExtra(key, id);
//			i.putExtra("groupName", groupName);
//			context.startActivity(i);
			searchIntoInfoListener.searchIntoInfo(clazz,id,groupName,key);
		}
	}

	public void setInvite(boolean isInvite) {
		this.isInvite = isInvite;
	}

	public void addSelect(Integer position) {
		selects.add(position);
	}
	
	public void addSingleSelect(Integer position){
		selects.clear();
		selects.add(position);
	}

	public void removeSelect(Integer position) {
		selects.remove(position);
	}
	
	public int getSelectItem(){
		if(selects.isEmpty())
			return -1;
		else
			return selects.get(0);
	}

	public ArrayList<Integer> getSelect(){
		return selects;
	}
	
	
	public void clearSelect(){
		selects.clear();
	}
	
	/**
	 * 设置是否显示人数
	 * 
	 * @param isShow
	 */
	public void setPersonNumber(boolean isShow) {
		this.isPersonNumber = isShow;
	}


	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
        indexStart = firstVisibleItem;
        indexEnd = firstVisibleItem + visibleItemCount;
        if(indexEnd > totalItemCount)
        	indexEnd = totalItemCount -1;
	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE){
            downImage(view);
			isRefresh = true;
		}else
			isRefresh = false;
	}

	private void downImage(AbsListView view) {
		for (; indexStart < indexEnd; indexStart++) {
			Object obj = data.get(indexStart);
			if(obj instanceof String)
				obj = mAppData.cacheInformation.get((String)obj);
			BaseInfoEntity entity = (BaseInfoEntity)obj;
//			String savepath = cus.getNormalHeadIcon();
			String path = entity.getNormalHeadIcon();
			ImageView image = (ImageView)view.findViewWithTag(indexStart);
			if(entity instanceof CustomerInfoEntity){
//				if(path.contains(FileUtils.getHeaderRootPath()))
//				   FileUtils.setImage(context, image, path, false,((CustomerInfoEntity) entity).getSex());
//				else{
				   imageLoader.displayImage(path,image,((CustomerInfoEntity) entity).getSex(), false);
//				}
			}else{
//				if(path.contains(FileUtils.getHeaderRootPath()))
//					FileUtils.setImage(context, image, path, true,"");
//				else{
				    imageLoader.displayImage(path,image, "", true);
//				}
			}
//			if(!path.contains(FileUtils.getHeaderRootPath()) && !path.contains("assets"))
//			  ((BaseInfoEntity)obj).setNormalHeadIcon(FileUtils.getHeaderRootPath()+path.substring(path.lastIndexOf("/")+1));
		}
	}
	
	/**
	 * 
	* @Title: setIntoInfoListener 
	* @Description: 设置监听器
	* @param @param infoListener    
	* @return void    
	* @throws
	 */
	public void setSearchIntoInfoListener(SearchIntoInfoListener searchIntoInfoListener){
		this.searchIntoInfoListener = searchIntoInfoListener;
	};

/**
 * 
* @ClassName: IntoInfoListener 
* @Description: 跳转信息的接口
* @author wangtao
* @date 2012-10-26 下午2:30:24
 */
  public interface SearchIntoInfoListener{
	/**
	 * 
	* @Title: intoInfo 
	* @Description: 跳转信息界面的方法
	* @param @param cl
	* @param @param id
	* @param @param name
	* @param @param key    
	* @return void    
	* @throws
	 */
	void searchIntoInfo(Class cl,String id ,String name,String key);
	
  }
}
